package com.huawei.user.service.impl;

import com.huawei.basic.constant.VerifyConstants;
import com.huawei.basic.exception.BusinessException;
import com.huawei.basic.util.MD5Utils;
import com.huawei.basic.util.StrUtils;
import com.huawei.user.domain.Logininfo;
import com.huawei.user.domain.User;
import com.huawei.user.dto.UserDto;
import com.huawei.user.mapper.LogininfoMapper;
import com.huawei.user.mapper.UserMapper;
import com.huawei.basic.service.impl.BaseServiceImpl;
import com.huawei.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void add(User user) {
        super.add(user);
    }

    @Override
    public void del(Long id) {
        super.del(id);
    }

    @Override
    public void update(User user) {
        super.update(user);
    }

    @Override
    public void register(User user) {
        //一：校验
        //1.空值校验 - 试一下
        if(StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())
                || StringUtils.isEmpty(user.getLogininfo().getUsername())
                || StringUtils.isEmpty(user.getLogininfo().getEmail()) || StringUtils.isEmpty(user.getLogininfo().getPhone())
                || StringUtils.isEmpty(user.getLogininfo().getPassword())){
            throw new BusinessException("数据不能为空");
        }
        //2.密码是否一致：不做，如果要做在t_logininfo加一个字段comfirmPassword即可

        //3.是否曾经入驻过
        User userTem = userMapper.loginByMessage(user);
        if(userTem != null){
            throw new BusinessException("已经注册，请直接登录。");
        }

        //二：添加到数据库
        //1.添加t_user
        Logininfo logininfo = user.getLogininfo();
        logininfoMapper.save(logininfo);

        //2.添加t_logininfo
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);

        //3.修改user_id的t_logininfo
        user.setLogininfoId(logininfo.getId());
        userMapper.update(user);
    }

    @Override
    public void phoneRegister(UserDto userDto) {

        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();
        //1.校验 - 空值校验
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(phoneCode) ||
                StringUtils.isEmpty(phone) || StringUtils.isEmpty(passwordRepeat) ){
            throw new BusinessException("数据不能为空");
        }

        //2.校验 - 密码一致校验
        if (!password.trim().equalsIgnoreCase(passwordRepeat.trim())){
            throw new BusinessException("两次密码不一致");
        }

        //3.校验 - 验证码是否过期 :  9527:441122222
        Object redisPhoneCode = redisTemplate.opsForValue().get(VerifyConstants.REGISTER_PREFIX + phone);
        if (redisPhoneCode==null){
            throw new BusinessException("手机验证码失效");
        }

        //4.校验 - 验证码是否正确
        if (!redisPhoneCode.toString().split(":")[0].equalsIgnoreCase(phoneCode)){
            throw new BusinessException("手机验证码错误");
        }

        //5.添加 - t_logininfo信息
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);

        //6.添加 - t_user信息
        //设置登录信息id
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);

    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //将和user相同的值赋给logininfo
        BeanUtils.copyProperties(user,logininfo);
        //设置为用户
        logininfo.setType(1);
        return logininfo;
    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());

        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String md5Pwd = MD5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setPassword(md5Pwd);
        return user;
    }

    @Override
    public void emailRegister(UserDto userDto) {
        String email = userDto.getEmail();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();
        String key = userDto.getKey();
        String imageCode = userDto.getImageCode();

        //1.校验 - 空值校验
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(key) ||
        StringUtils.isEmpty(email) || StringUtils.isEmpty(passwordRepeat) || StringUtils.isEmpty(imageCode) ){
            throw new BusinessException("数据不能为空");
        }

        //2.校验 - 密码一致校验
        if (!password.trim().equalsIgnoreCase(passwordRepeat.trim())){
            throw new BusinessException("两次密码不一致");
        }
        //2.1.图片验证码是否过期
        Object imageCodeValue = redisTemplate.opsForValue().get(key);
        if (imageCodeValue==null){
            throw new BusinessException("图片验证码过期，请重新输入");
        }
        //2.2.图片验证码是否正确
        if (!imageCodeValue.toString().equalsIgnoreCase(imageCode)){
            throw new BusinessException("错误的图片验证码，请重新输入");
        }
        //3.校验 - 邮箱是否被注册 - 查询t_user表
        User user1 = userMapper.loadByPhone(email);
        if(user1 != null){
            throw new BusinessException("该邮箱已经注册，请直接登录!");
        }


        //5.添加 - t_logininfo信息
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);

        //6.添加 - t_user信息
        //设置登录信息id
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);

    }


}
